package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Address;
import com.dropdb.demo.bean.AddressExample;
import com.dropdb.demo.bean.vo.DetailAddressVO;
import com.dropdb.demo.bean.vo.WxAddressVO;
import com.dropdb.demo.mapper.AddressMapper;
import com.dropdb.demo.mapper.RegionMapper;
import com.dropdb.demo.service.WxAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:cheyanjun
 * @date:2020/06/30 23:57
 */
@Service
public class WxAddressServiceImpl implements WxAddressService {
    @Autowired
    AddressMapper addressMapper;

    @Autowired
    RegionMapper regionMapper;

    /**
     * 获取该用户的所有地址记录
     * @param userId
     * @return
     */
    @Override
    public List<WxAddressVO> getAddressList(int userId) {
        List<WxAddressVO> addressVOS = addressMapper.queryList(userId);
        return addressVOS;
    }

    /**
     * 获取详细地址
     * @param id
     * @return
     */
    @Override
    public DetailAddressVO getAddressDetail(int id) {
        //查询存储在address表中的当前用户信息
        DetailAddressVO addressVO = addressMapper.queryDetail(id);
        //根据areaId查询region表获得areaName
        addressVO.setAreaName(regionMapper.queryName(addressVO.getAreaId()));
        //根据provinceId查询region表获得provinceName
        addressVO.setProvinceName(regionMapper.queryName(addressVO.getProvinceId()));
        //根据cityId查询region表获得cityName
        addressVO.setCityName(regionMapper.queryName(addressVO.getCityId()));
        return addressVO;
    }

    /**
     *保存地址更改
     * @param address
     */
    @Override
    public void saveAddress(Address address) {
        AddressExample addressExample = new AddressExample();
        addressExample.createCriteria().andIdEqualTo(address.getId());
        addressMapper.updateByExample(address,addressExample);
    }

    /**
     * 插入新的地址记录
     * @param address
     * @return 最后一次插入数据的主键
     */
    @Override
    public int addAddress(Address address) {
        int id = addressMapper.insert(address);
        return id;
    }

    /**
     * 根据主键删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Integer id) {
        addressMapper.deleteByPrimaryKey(id);
    }

    /**
     * 更新所有当前user_id的is_default=false
     * @param userId
     */
    @Override
    public void updateIsDefault(Integer userId) {
        addressMapper.updateByUserId(userId);
    }


}
